import axios from 'axios'
import type { AxiosInstance, AxiosRequestConfig } from 'axios'
import type { responseType } from '@/api/type'
import { ElMessage } from 'element-plus'
import { getToken } from './token'
import { useUserStore } from "@/stores/user";

// 添加请求队列
const pendingRequests = new Map<string, () => void>();

const service: AxiosInstance = axios.create({
    baseURL: import.meta.env.VITE_APP_BASE_API,
    withCredentials: false,
    timeout: 3 * 1000
})

service.interceptors.request.use((config) => {
    // 生成请求标识
    const requestKey = generateRequestKey(config);
    // 如果请求已经在队列中，则取消该请求
    // if (pendingRequests.has(requestKey)) {
    //     const cancelTokenSource = axios.CancelToken.source();
    //     config.cancelToken = cancelTokenSource.token;
    //     cancelTokenSource.cancel(`重复请求: ${requestKey}`);
    //     console.log("本次请求是一个重复请求")
    //     ElMessage({ message: '重复请求，请刷新再发送！', type: 'error' })
    // } else {
    //     // 否则，将请求添加到队列中
    //     config.cancelToken = new axios.CancelToken((cancel) => {
    //         pendingRequests.set(requestKey, cancel);
    //     });
    // }
    config.headers['user-type'] = 'admin'//表示该请求来自后台系统
    if (getToken()) {
        config.headers['token'] = getToken(); //携带token
        config.headers['Content-type'] = 'application/json';
    }

    return config;
}, (error) => {
    return Promise.reject(error)
})

service.interceptors.response.use((response) => {
    // 生成请求标识
    const requestKey = generateRequestKey(response.config);
    // 请求完成后，从队列中移除
    pendingRequests.delete(requestKey);
    let { code, msg } = response.data
    switch (code) {
        case 200:
            if(response.config.method==="post"){
                ElMessage({ message: msg || '添加成功', type: 'success' })
            }
            else if(response.config.method==="put"){
                ElMessage({ message: msg || '修改成功', type: 'success' })
            }
            break;
        case 401:
            ElMessage({ message: msg || '登录过期', type: 'error' })
            const userStore = useUserStore()
            userStore.logout();
            break;
        default:
            ElMessage({ message: msg || '无权访问！', type: 'error' })
            console.log("请求异常,请前往请求工具类中查看！")
            return Promise.reject(msg)
    }
    return response.data;
}, (error) => {
    // 生成请求标识
    const requestKey = generateRequestKey(error.config);
    // 请求完成后，从队列中移除
    pendingRequests.delete(requestKey);

    if (axios.isCancel(error)) {
        console.log(error.message);
    } else {
        let status = error.response.status;
        console.log(status);
    }
    ElMessage({ message: error, type: 'error' })
    return Promise.reject(error)
})

/**
 * 生成请求标识
 * @param config
 * @returns
 */
function generateRequestKey(config: AxiosRequestConfig): string {
    return [config.method, config.url, JSON.stringify(config.params), JSON.stringify(config.data)].join('&');
}

/**
 * 所有返回值类型为responseType{code,msg,data}，并允许对data指定类型
 * @param config
 * @returns
 */
export function request<T>(config: AxiosRequestConfig): Promise<responseType<T>> {
    return service(config);
}
export default request;
